package com.ledi.guns.modular.ledipay.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.BillAlipayMapper;
import com.ledi.guns.common.persistence.dao.BillDetailMapper;
import com.ledi.guns.common.persistence.dao.BillItemMapper;
import com.ledi.guns.common.persistence.dao.BillMapper;
import com.ledi.guns.common.persistence.dao.BillWeixinMapper;
import com.ledi.guns.common.persistence.dao.ClassInfoMapper;
import com.ledi.guns.common.persistence.dao.SchoolInfoMapper;
import com.ledi.guns.common.persistence.dao.SchoolPayItemMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.Bill;
import com.ledi.guns.common.persistence.model.BillAlipay;
import com.ledi.guns.common.persistence.model.BillDetail;
import com.ledi.guns.common.persistence.model.BillItem;
import com.ledi.guns.common.persistence.model.BillWeixin;
import com.ledi.guns.common.persistence.model.ClassInfo;
import com.ledi.guns.common.persistence.model.SchoolInfo;
import com.ledi.guns.common.persistence.model.SchoolPayItem;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.core.util.DateUtil;
import com.ledi.guns.core.util.PayUtil;
import com.ledi.guns.core.util.StringUtil;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.ScanCode.Face2FacePay;
import com.ledi.guns.modular.ledipay.controller.req.ScanCode.PayInfo;
import com.ledi.guns.modular.ledipay.controller.req.ScanCode.PayItem;
import com.ledi.guns.modular.ledipay.controller.req.ScanCode.QueryDetailInfo;
import com.ledi.guns.modular.ledipay.service.BillTimingService;
import com.ledi.guns.modular.ledipay.service.IScanCodeService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.ScanCodeServiceImpl.java<br/>
 * 初始作者： 许芬<br/>
 * 创建日期： 2018年1月4日<br/>
 * 功能说明： 这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (橘子股份-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
public class ScanCodeServiceImpl implements IScanCodeService {

	protected final static Logger logger = LoggerFactory.getLogger(ScanCodeServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ClassInfoMapper classInfoMapper;
	@Autowired
	private SchoolInfoMapper schoolInfoMapper;
	@Autowired
	private BillDetailMapper billDetailMapper;
	@Autowired
	private BillTimingService billTimingService;

	@Autowired
	private BillWeixinMapper billWeixinMapper;
	@Autowired
	private BillAlipayMapper billAlipayMapper;
	@Autowired
	private BillItemMapper billItemMapper;
	@Autowired
	BillStreamServiceImpl streamService;
	@Value("${weixin.appid}")
	private String appid;
	@Value("${weixin.secret}")
	private String secret;
	@Value("${weixin.openIdUrl}")
	private String openIdUrl;
	@Value("${weixin.notifyUrl}")
	private String notifyUrl;
	@Value("${weixin.mchId}")
	private String mchId;
	@Value("${weixin.shhkey}")
	private String shhkey;
	@Value("${weixin.weixinPayUrl}")
	private String weixinPayUrl;

	@Value("${ali.dangmianfuUrl}")
	private String dangmianfuUrl;

	@Autowired
	private EduPayAliObserver eduPayAliObserver;
	@Autowired
	private EduPayWexinObserver eduPayWexinObserver;
	@Autowired
	private SchoolPayItemMapper schoolPayItemMapper;
	@Autowired
	private BillMapper billMapper;

	@Override
	@Transactional
	public Map<String, String> pay(PayInfo payInfo, HttpServletRequest request, HttpServletResponse response) {

		BigDecimal totalDetail = null;
		Map<String, String> mapResult = new HashMap<String, String>();

		/*------1.校验参数信息------- */
		logger.error("----------------入参" + payInfo.toString());
		// 校验手机号
		if (!StringUtil.isMobile(payInfo.getParentMobile())) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "手机号");
		}
		// 获取金额
		try {
			totalDetail = new BigDecimal(payInfo.getTotalDetail());

		} catch (Exception e) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "缴费金额");
		}
		// 金额不能是负数
		if (totalDetail != null && totalDetail.compareTo(new BigDecimal("0")) < 0) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "缴费金额");
		}
		if (SystemConstans.PAY_WAY_WEIXIN.equals(payInfo.getPayWay().trim())
				&& totalDetail.compareTo(new BigDecimal("200000")) > 0) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "缴费金额，缴费金额不能大于200000");
		}
		if (SystemConstans.PAY_WAY_ALI.equals(payInfo.getPayWay().trim())
				&& totalDetail.compareTo(new BigDecimal("100000000")) > 0) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "缴费金额，缴费金额不能大于100000000");
		}
		// 校验用户
		User user = userMapper.selectById(payInfo.getUserId());
		if (user == null || !user.getStatus().equals(1)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "用户不存在");
		}
		// 校验用户和学校是否匹配
		Long schoolId = user.getSchoolId();
		if (!payInfo.getSchoolId().equals(schoolId)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "用户和学校不匹配");
		}
		// 校验学校是否存在
		SchoolInfo schoolInfo = schoolInfoMapper.selectById(schoolId);
		if (schoolInfo == null || !schoolInfo.getIsDelete().equals(0)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "学校不存在");
		}
		SortedMap<String, String> commentSign = new TreeMap<String, String>();
		commentSign.put("userId", payInfo.getUserId() + "");
		commentSign.put("schoolId", payInfo.getSchoolId() + "");
		commentSign.put("key", user.getPassword());
		String comment = PayUtil.createSign(commentSign);
		if (!comment.equalsIgnoreCase(payInfo.getComments())) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "签名失败");
		}

		/*------2.获取账单明细ID----------*/
		// 账单明细ID
		String billDetailId = PayUtil.getBillDetailId();
		boolean isBillDetailId = true;
		do {
			// 校验账单是否可用
			List<BillDetail> queryBillDetailList = billDetailMapper
					.selectList(new EntityWrapper<BillDetail>()
							.eq("is_delete", 0)
							.eq("bill_detail_id", billDetailId));
			if (queryBillDetailList == null || queryBillDetailList.size() == 0) {
				isBillDetailId = false;
				break;
			}
			billDetailId = PayUtil.getBillDetailId();
		} while (isBillDetailId);

		/*------3.将信息入库----------*/

		ClassInfo classInfo = new ClassInfo();
		classInfo.setSchoolId(schoolId);
		classInfo.setId(payInfo.getClassId());
		classInfo.setIsDelete(0);
		classInfo = classInfoMapper.selectOne(classInfo);
		if (classInfo == null) {
			classInfo = new ClassInfo();
			classInfo.setSchoolId(schoolId);
			classInfo.setName(payInfo.getClassName());
			classInfo.setIsDelete(0);
			classInfo.setCreateTime(new Date());
			classInfo.setCreatorId(Long.valueOf(user.getId()));
			classInfo.setCreatorRole(user.getRoleid());
			classInfoMapper.insert(classInfo);
		}

		BillDetail billDetail = new BillDetail();
		billDetail.setTotalDetail(totalDetail);
		billDetail.setBillDetailId(billDetailId);
		billDetail.setBillId(SystemConstans.BILL_SCAN_CODE);
		billDetail.setSchoolId(schoolId);
		billDetail.setClassId(classInfo.getId());
		billDetail.setTotalDetail(billDetail.getTotalDetail());
		billDetail.setBillStatus(SystemConstans.BILL_STATUS_UNSEND);
		billDetail.setStudentName(payInfo.getStudentName());
		billDetail.setParentMobile(payInfo.getParentMobile());
		billDetail.setBillDetailBeginTime(new Date());
		billDetail.setPayWay(payInfo.getPayWay());
		billDetail.setComment(payInfo.getItemName());

		billDetail.setIsDelete(0);
		billDetail.setCreateTime(new Date());
		billDetail.setCreatorId(Long.valueOf(user.getId()));
		billDetail.setCreatorRole(user.getRoleid());
		int insertBillDetail = billDetailMapper.insert(billDetail);
		if (insertBillDetail < 1) {
			throw new AppCheckException("school.zhangdan.scan.zhangdan.file.code",
					"school.zhangdan.scan.zhangdan.file.message");
		}
		BillItem billItem = new BillItem();
		billItem.setBilllDetailId(billDetailId);
		billItem.setItemName("暂无缴费名称");
		billItem.setItemMoney(totalDetail);
		// 添加缴费项目表
		int insertBillItem = billItemMapper.insert(billItem);
		if (insertBillItem < 1) {
			throw new AppCheckException("school.zhangdan.scan.zhangdan.file.code",
					"school.zhangdan.scan.zhangdan.file.message");
		}

		/*------4.区分是否是微信还是支付宝支付----------*/
		if (SystemConstans.PAY_WAY_WEIXIN.equals(payInfo.getPayWay().trim())) {
			mapResult = eduPayWexinObserver.createWeixinPay(payInfo.getBillDetailId(), payInfo.getCode(), billDetailId,
					schoolInfo.getSubMchId(),
					totalDetail,
					request,
					response, billDetail);

			billTimingService.addBillToRedisList(billDetailId, DateUtil.addDaysToDate(new Date(), 1),
					SystemConstans.PAY_WAY_WEIXIN);
			// 随机数
			String nonce_str = PayUtil.getNonceStr();
			// 时间戳
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			finalpackage.put("appId", appid);
			finalpackage.put("timeStamp", timestamp);
			finalpackage.put("nonceStr", nonce_str);
			finalpackage.put("package", "prepay_id=" + mapResult.get("prepay_id"));
			finalpackage.put("signType", "MD5");
			finalpackage.put("key", shhkey);

			String paySign = PayUtil.createSign(finalpackage);

			logger.error("-----------" + finalpackage.toString() + "签名=" + paySign);
			mapResult.put("sign", paySign);
			mapResult.put("nonce_str", nonce_str);
			mapResult.put("timeStamp", timestamp);
			mapResult.put("payWay", SystemConstans.PAY_WAY_WEIXIN);
			mapResult.put("billDetailId", billDetailId);
		} else if (SystemConstans.PAY_WAY_ALI.equals(payInfo.getPayWay().trim())) {
			Bill bill = new Bill();
			bill.setName("扫一扫缴费");
			bill.setBillEndTime(DateUtil.addDaysToDate(new Date(), 1));
			eduPayAliObserver.sendBillDetail(bill, billDetail, schoolInfo, 1);
			BillDetail queryBillDetail = billDetailMapper.selectById(billDetail.getId());
			if (!queryBillDetail.getBillStatus().equals(SystemConstans.BILL_STATUS_SEND_SUCCESS)) {
				throw new AppCheckException("school.zhangdan.scan.user.file.code",
						"school.zhangdan.scan.user.file.message", queryBillDetail.getFileReason());
			}
			billTimingService.addBillToRedisList(billDetailId, DateUtil.addDaysToDate(new Date(), 1),
					SystemConstans.PAY_WAY_ALI);
			String schoolCode = schoolInfo.getSchoolNo();

			String parentMobile = billDetail.getParentMobile();
			BillAlipay queryBillAlipay = new BillAlipay();
			queryBillAlipay.setBillDetailId(billDetailId);
			BillAlipay billAlipay = billAlipayMapper.selectOne(queryBillAlipay);
			String orderno = billAlipay.getAlipayOrderNo();
			String studentNo = billAlipay.getAlipayStudentNo();

			String resultUrl = dangmianfuUrl + "&schoolCode=" + schoolCode
					+ "&studentNo=" + studentNo + "&value=" + parentMobile + "&isvNo=" + billDetailId + "&orderno="
					+ orderno
					+ "&__webview_options__=pullRefresh%3DYES";
			logger.info(resultUrl);
			resultUrl = java.net.URLEncoder.encode(resultUrl);
			mapResult.put("resultUrl", resultUrl);
			mapResult.put("payWay", SystemConstans.PAY_WAY_ALI);
			mapResult.put("billDetailId", billDetailId);
		} else {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "支付方式错误");
		}

		return mapResult;
	}

	@Override
	@Transactional
	public void weixinNotify(String resultStr) {

		Map<String, Object> resultMap = PayUtil.parseXmlToList(resultStr);
		String out_trade_no = null;
		String return_code = (String) resultMap.get("return_code");
		if (return_code.equals("SUCCESS")) {
			String result_code = (String) resultMap.get("result_code");
			if (result_code.equals("SUCCESS")) {
				String transaction_id = (String) resultMap.get("transaction_id");
				String openid = (String) resultMap.get("openid");
				String time_end = (String) resultMap.get("time_end");
				String bank_type = (String) resultMap.get("bank_type");
				String total_fee = (String) resultMap.get("total_fee");
				out_trade_no = (String) resultMap.get("out_trade_no");
				BillDetail billDetail = new BillDetail();
				billDetail.setBillDetailId(out_trade_no);
				billDetail = billDetailMapper.selectOne(billDetail);
				billDetail.setPayTime(DateUtil.parseDate1(time_end));
				billDetail.setBillStatus(SystemConstans.BILL_STATUS_FINISH);
				billDetail.setTotalDetail(new BigDecimal(total_fee).divide(new BigDecimal(100)));
				Integer updateById = billDetailMapper.updateById(billDetail);
				if (updateById < 1) {
					logger.error("【微信支付回调插库失败】");
					try {
						throw new Exception();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				BillWeixin billWeixin = new BillWeixin();
				billWeixin.setBillDetailId(out_trade_no);
				billWeixin = billWeixinMapper.selectOne(billWeixin);
				billWeixin.setPayTime(DateUtil.parseDate1(time_end));
				billWeixin.setWeixinTransactionId(transaction_id);
				billWeixin.setBillStatus(6);
				Integer insert = billWeixinMapper.updateById(billWeixin);
				if (insert < 1) {
					logger.error("【微信支付回调插库失败】");
					try {
						throw new Exception();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				streamService.billStream("同步支付状态", out_trade_no, SystemConstans.API_INVOKE_TYPE_RECEIVE,
						SystemConstans.PAY_WAY_WEIXIN, resultMap.toString(), "");
			}
		}
	}

	@Override
	public com.ledi.guns.modular.ledipay.controller.req.ScanCode.SchoolInfo findSchoolInfo(Long id) {

		com.ledi.guns.modular.ledipay.controller.req.ScanCode.SchoolInfo schoolInfoResult = new com.ledi.guns.modular.ledipay.controller.req.ScanCode.SchoolInfo();
		SchoolInfo schoolInfo = schoolInfoMapper.selectById(id);

		if (schoolInfo == null || !schoolInfo.getIsDelete().equals(0)) {
			throw new AppCheckException("school.zhangdan.scan.school.code",
					"school.zhangdan.scan.school.message", "查询学校不存在");
		}

		List<ClassInfo> classList = classInfoMapper.selectList(new EntityWrapper<ClassInfo>()
				.eq("is_delete", 0)
				.eq("school_id", id));
		schoolInfoResult.setId(id);
		schoolInfoResult.setSchoolName(schoolInfo.getSchoolName());
		List<com.ledi.guns.modular.ledipay.controller.req.ScanCode.ClassInfo> list = new ArrayList<com.ledi.guns.modular.ledipay.controller.req.ScanCode.ClassInfo>();
		for (ClassInfo classInfo : classList) {
			com.ledi.guns.modular.ledipay.controller.req.ScanCode.ClassInfo classInfoResult = new com.ledi.guns.modular.ledipay.controller.req.ScanCode.ClassInfo();
			classInfoResult.setId(classInfo.getId());
			classInfoResult.setClassName(classInfo.getName());
			list.add(classInfoResult);
		}
		schoolInfoResult.setClassInfoList(list);
		return schoolInfoResult;
	}

	@Override
	public QueryDetailInfo findDetailInfo(String billDetailId) {

		QueryDetailInfo queryDetailInfo = billDetailMapper.findDetailInfo(billDetailId);
		return queryDetailInfo;
	}

	/**
	 * 方法描述: [当面付账单.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月22日-下午8:16:06<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public Map<String, String> face2FacePrePay(Face2FacePay payInfo, HttpServletRequest request, HttpServletResponse response) {

		Map<String, String> mapResult = new HashMap<String, String>();

		/*------1.校验参数信息------- */
		logger.error("----------------入参" + payInfo.toString());
		// 校验手机号
		if (!StringUtil.isMobile(payInfo.getParentMobile())) {
			throw new AppCheckException("school.zhangdan.scan.moblie.file.code",
					"school.zhangdan.scan.moblie.file.message", "手机号");
		}

		Long billId = payInfo.getBillId();
		Bill bill = new Bill();
		bill.setId(billId);
		bill.setIsDelete(SystemConstans.NO);
		bill.setBillType(SystemConstans.TWO);
		Bill needPayBill = billMapper.selectOne(bill);
		if (needPayBill == null) {
			throw new AppCheckException("school.zhangdan.scan.bill.notEixt.code", "school.zhangdan.scan.bill.notEixt.message");
		}
		// 校验用户
		User user = userMapper.selectById(payInfo.getUserId());
		if (user == null || !user.getStatus().equals(1)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "用户不存在");
		}
		// 校验用户和学校是否匹配
		Long schoolId = user.getSchoolId();
		if (!payInfo.getSchoolId().equals(schoolId)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "用户和学校不匹配");
		}
		// 校验学校是否存在
		SchoolInfo schoolInfo = schoolInfoMapper.selectById(schoolId);
		if (schoolInfo == null || !schoolInfo.getIsDelete().equals(0)) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "学校不存在");
		}
		SortedMap<String, String> commentSign = new TreeMap<String, String>();
		commentSign.put("userId", payInfo.getUserId() + "");
		commentSign.put("schoolId", payInfo.getSchoolId() + "");
		commentSign.put("key", user.getPassword());
		String comment = PayUtil.createSign(commentSign);
		if (!comment.equalsIgnoreCase(payInfo.getSign())) {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "签名失败");
		}
		/*------2.获取账单明细ID----------*/
		// 账单明细ID
		String billDetailId = PayUtil.getBillDetailId();
		boolean isBillDetailId = true;
		do {
			// 校验账单是否可用
			List<BillDetail> queryBillDetailList = billDetailMapper
					.selectList(new EntityWrapper<BillDetail>()
							.eq("is_delete", 0)
							.eq("bill_detail_id", billDetailId));
			if (queryBillDetailList == null || queryBillDetailList.size() == 0) {
				isBillDetailId = false;
				break;
			}
			billDetailId = PayUtil.getBillDetailId();
		} while (isBillDetailId);

		/*------3.将信息入库----------*/

		ClassInfo classInfo = new ClassInfo();
		classInfo.setSchoolId(schoolId);
		classInfo.setId(payInfo.getClassId());
		classInfo.setIsDelete(0);
		classInfo = classInfoMapper.selectOne(classInfo);
		if (classInfo == null) {
			classInfo = new ClassInfo();
			classInfo.setSchoolId(schoolId);
			classInfo.setName(payInfo.getClassName());
			classInfo.setIsDelete(0);
			classInfo.setCreateTime(new Date());
			classInfo.setCreatorId(Long.valueOf(user.getId()));
			classInfo.setCreatorRole(user.getRoleid());
			classInfoMapper.insert(classInfo);
		}

		BillDetail billDetail = new BillDetail();
		billDetail.setBillDetailId(billDetailId);
		billDetail.setBillId(billId);
		billDetail.setSchoolId(schoolId);
		billDetail.setClassId(classInfo.getId());
		billDetail.setBillStatus(SystemConstans.BILL_STATUS_UNSEND);
		billDetail.setStudentName(payInfo.getStudentName());
		billDetail.setParentMobile(payInfo.getParentMobile());
		billDetail.setBillDetailBeginTime(new Date());
		billDetail.setPayWay(payInfo.getPayWay());
		billDetail.setComment(payInfo.getComments());
		billDetail.setIsDelete(0);
		billDetail.setCreateTime(new Date());
		billDetail.setCreatorId(Long.valueOf(user.getId()));
		billDetail.setCreatorRole(user.getRoleid());
		// 订单收费项明细
		List<SchoolPayItem> schoolPayItems = schoolPayItemMapper.selectByBillId(bill.getId(), schoolId);
		BigDecimal totalDetail = new BigDecimal(0);

		// 必选金额
		BigDecimal needSelected = new BigDecimal(0);
		if (schoolPayItems.size() != 0) {
			for (SchoolPayItem item : schoolPayItems) {
				BigDecimal money = item.getMoney();
				if (item.getFlag() == SystemConstans.TWO) {
					money = money.negate();
				}
				if (item.getFlag() > 0) {
					needSelected = needSelected.add(money);
				}
				totalDetail = totalDetail.add(money);
			}
			if (needSelected.compareTo(new BigDecimal(0)) <= 0) {
				throw new AppCheckException("school.schoolPayItem.bill.oversized.code", "school.schoolPayItem.bill.oversized.message");
			}
		} else {
			throw new AppCheckException("school.schoolPayItem.bill.noExit.code", "school.schoolPayItem.bill.noExit.message");
		}
		billDetail.setTotalDetail(totalDetail);
		billDetail.setPayItem(JSON.toJSONString(schoolPayItems));
		int insertBillDetail = billDetailMapper.insert(billDetail);
		if (insertBillDetail < 1) {
			throw new AppCheckException("school.zhangdan.scan.zhangdan.file.code",
					"school.zhangdan.scan.zhangdan.file.message");
		}
		BillItem billItem = new BillItem();
		billItem.setBilllDetailId(billDetailId);
		billItem.setItemName("暂无缴费名称");
		billItem.setItemMoney(totalDetail);
		// 添加缴费项目表
		int insertBillItem = billItemMapper.insert(billItem);
		if (insertBillItem < 1) {
			throw new AppCheckException("school.zhangdan.scan.zhangdan.file.code",
					"school.zhangdan.scan.zhangdan.file.message");
		}
		/*------4.区分是否是微信还是支付宝支付----------*/
		if (SystemConstans.PAY_WAY_WEIXIN.equals(payInfo.getPayWay().trim())) {

			List<PayItem> payItems = payInfo.getPayItems();
			Double totalDetails = payItems.stream().mapToDouble(PayItem::getMoney).sum();
			mapResult = eduPayWexinObserver.createWeixinPay(null, payInfo.getCode(), billDetailId,
					schoolInfo.getSubMchId(),
					new BigDecimal(totalDetails),
					request,
					response, billDetail);

			billTimingService.addBillToRedisList(billDetailId, DateUtil.addDaysToDate(new Date(), 1),
					SystemConstans.PAY_WAY_WEIXIN);
			// 随机数
			String nonce_str = PayUtil.getNonceStr();
			// 时间戳
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			finalpackage.put("appId", appid);
			finalpackage.put("timeStamp", timestamp);
			finalpackage.put("nonceStr", nonce_str);
			finalpackage.put("package", "prepay_id=" + mapResult.get("prepay_id"));
			finalpackage.put("signType", "MD5");
			finalpackage.put("key", shhkey);
			String paySign = PayUtil.createSign(finalpackage);
			logger.error("-----------" + finalpackage.toString() + "签名=" + paySign);
			mapResult.put("sign", paySign);
			mapResult.put("nonce_str", nonce_str);
			mapResult.put("timeStamp", timestamp);
			mapResult.put("payWay", SystemConstans.PAY_WAY_WEIXIN);
			mapResult.put("billDetailId", billDetailId);
		} else if (SystemConstans.PAY_WAY_ALI.equals(payInfo.getPayWay().trim())) {

			eduPayAliObserver.sendBillDetail(needPayBill, billDetail, schoolInfo, 1);
			BillDetail queryBillDetail = billDetailMapper.selectById(billDetail.getId());
			if (!queryBillDetail.getBillStatus().equals(SystemConstans.BILL_STATUS_SEND_SUCCESS)) {
				throw new AppCheckException("school.zhangdan.scan.user.file.code",
						"school.zhangdan.scan.user.file.message", queryBillDetail.getFileReason());
			}
			billTimingService.addBillToRedisList(billDetailId, DateUtil.addDaysToDate(new Date(), 1),
					SystemConstans.PAY_WAY_ALI);
			String schoolCode = schoolInfo.getSchoolNo();

			String parentMobile = billDetail.getParentMobile();
			BillAlipay queryBillAlipay = new BillAlipay();
			queryBillAlipay.setBillDetailId(billDetailId);
			BillAlipay billAlipay = billAlipayMapper.selectOne(queryBillAlipay);
			String orderno = billAlipay.getAlipayOrderNo();
			String studentNo = billAlipay.getAlipayStudentNo();

			// String resultUrl = jiaofeixiangqing + "&schoolCode=" + schoolCode
			// + "&studentNo=" + studentNo + "&value=" + parentMobile + "&orderno="
			// + orderno
			// + "&__webview_options__=pullRefresh%3DYES";
			String resultUrl = dangmianfuUrl + "&schoolCode=" + schoolCode
					+ "&studentNo=" + studentNo + "&value=" + parentMobile + "&isvNo=" + billDetailId + "&orderno="
					+ orderno
					+ "&__webview_options__=pullRefresh%3DYES";

			logger.info(resultUrl);
			resultUrl = java.net.URLEncoder.encode(resultUrl);
			mapResult.put("resultUrl", resultUrl);
			mapResult.put("payWay", SystemConstans.PAY_WAY_ALI);
			mapResult.put("billDetailId", billDetailId);
		} else {
			throw new AppCheckException("school.zhangdan.scan.user.file.code",
					"school.zhangdan.scan.user.file.message", "支付方式错误");
		}

		return mapResult;
	}

}
